<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class TtsService
{
    public function getAccessToken()
    {

        if (Cache::has('access_token')){
            return  Cache::get('access_token');
        }

        $result = Http::post('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=iX0xFwU4gq6aEn8FWnZ8EwLb&client_secret=eT53QleYaWXVFKnJ87F85gtrXzPYdeKW')->json();

        if (isset($result['access_token'])){
            Cache::put('access_token',$result['access_token'],$result['expires_in']);
            return  $result['access_token'];
        }
        return  '';
    }


    public function ttsCreate(string $text)
    {
        $result =  Http::post('https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token='.$this->getAccessToken(),[
            'text' => [$text],
            'lang' => 'zh'
        ])->json();

        if (isset($result['task_id'])){
            return $result['task_id'];
        }
        return '';
    }


    public function ttsQuery(array $task_ids)
    {
        $result = Http::post('https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token='.$this->getAccessToken(),[
            'task_ids' => $task_ids
        ])->json();

        if (isset($result['tasks_info'])){
            return $result['tasks_info'];
        }

        return  [];
    }

}
